import * as vscode from 'vscode';

export class JGEViewProvider implements vscode.WebviewViewProvider {
    public static readonly viewType = 'jge-rs.view';
    private _view?: vscode.WebviewView;
    private _status: 'disconnected' | 'connecting' | 'connected' = 'disconnected';
    private _serverStatus: 'stopped' | 'running' = 'stopped';

    constructor(private readonly _extensionUri: vscode.Uri) { }

    public setStatus(status: 'disconnected' | 'connecting' | 'connected') {
        this._status = status;
        this._updateView();
    }

    public setServerStatus(status: 'stopped' | 'running') {
        this._serverStatus = status;
        this._updateView();
    }

    public resolveWebviewView(
        webviewView: vscode.WebviewView,
        context: vscode.WebviewViewResolveContext,
        _token: vscode.CancellationToken
    ) {
        this._view = webviewView;

        webviewView.webview.options = {
            enableScripts: true,
            localResourceRoots: [this._extensionUri]
        };

        webviewView.webview.html = this._getHtmlForWebview(webviewView.webview);

        webviewView.webview.onDidReceiveMessage(data => {
            switch (data.command) {
                case 'toggleConnection':
                    vscode.commands.executeCommand('jge-rs.toggleConnection');
                    break;
                case 'toggleServer':
                    vscode.commands.executeCommand('jge-rs.toggleServer');
                    break;
                case 'sendDebug':
                    vscode.commands.executeCommand('jge-rs.sendDebug', data.content);
                    break;
                case 'sendLuaToJson':
                    vscode.commands.executeCommand('jge-rs.sendLuaToJson', data.content);
                    break;
                case 'openSettings':
                    vscode.commands.executeCommand('jge-rs.openSettings');
                    break;
            }
        });

        webviewView.onDidChangeVisibility(() => {
            if (webviewView.visible) {
                this._updateView();
            }
        });

        setTimeout(() => {
            this._updateView();
        }, 100);
    }

    private _updateView() {
        if (this._view) {
            this._view.webview.postMessage({
                command: 'updateStatus',
                status: this._status,
                serverStatus: this._serverStatus
            });
        }
    }

    private _getHtmlForWebview(webview: vscode.Webview) {
        const styles = `
            <style>
                body {
                    padding: 10px;
                    color: var(--vscode-editor-foreground);
                    background-color: var(--vscode-editor-background);
                    font-family: var(--vscode-font-family);
                    font-size: var(--vscode-font-size);
                }
                .header-container {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    border-bottom: 1px solid var(--vscode-editorWidget-border);
                    margin-bottom: 15px;
                    padding-bottom: 5px;
                }
                .tab-container {
                    display: flex;
                    flex: 1;
                }
                .tab {
                    padding: 8px 16px;
                    cursor: pointer;
                    border-bottom: 2px solid transparent;
                    color: var(--vscode-editor-foreground);
                    font-size: 13px;
                }
                .tab:hover {
                    background-color: var(--vscode-list-hoverBackground);
                }
                .tab.active {
                    border-bottom-color: var(--vscode-focusBorder);
                    font-weight: bold;
                    color: var(--vscode-button-foreground);
                }
                .settings-icon {
                    cursor: pointer;
                    padding: 4px;
                    border-radius: 3px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    transition: background-color 0.2s;
                }
                .settings-icon:hover {
                    background-color: var(--vscode-list-hoverBackground);
                }
                .settings-icon svg {
                    width: 16px;
                    height: 16px;
                    fill: var(--vscode-editor-foreground);
                }
                .tab-content {
                    padding: 10px;
                    display: none;
                }
                .tab-content.active {
                    display: block;
                }
                .connection-button {
                    padding: 8px 16px;
                    margin: 10px 0;
                    background-color: var(--vscode-button-background);
                    color: var(--vscode-button-foreground);
                    border: none;
                    cursor: pointer;
                    border-radius: 2px;
                    min-width: 100px;
                }
                .connection-button:hover {
                    background-color: var(--vscode-button-hoverBackground);
                }
                .connection-button.connected {
                    background-color: var(--vscode-charts-green);
                }
                .connection-button.connecting {
                    background-color: var(--vscode-charts-yellow);
                }
                .connection-button.disconnected {
                    background-color: var(--vscode-charts-red);
                }
                .server-button {
                    padding: 8px 16px;
                    margin: 10px 0;
                    background-color: var(--vscode-button-background);
                    color: var(--vscode-button-foreground);
                    border: none;
                    cursor: pointer;
                    border-radius: 2px;
                    min-width: 100px;
                }
                .server-button:hover {
                    background-color: var(--vscode-button-hoverBackground);
                }
                .server-button.running {
                    background-color: var(--vscode-charts-green);
                }
                .server-button.stopped {
                    background-color: var(--vscode-charts-red);
                }
                .debug-input {
                    width: 100%;
                    height: 200px;
                    margin-bottom: 10px;
                    background-color: var(--vscode-input-background);
                    color: var(--vscode-input-foreground);
                    border: 1px solid var(--vscode-input-border);
                    padding: 8px;
                    font-family: var(--vscode-font-family);
                    resize: vertical;
                }
                .debug-button {
                    padding: 8px 16px;
                    background-color: var(--vscode-button-background);
                    color: var(--vscode-button-foreground);
                    border: none;
                    cursor: pointer;
                    border-radius: 2px;
                }
                .debug-button:hover {
                    background-color: var(--vscode-button-hoverBackground);
                }
                .debug-button:disabled {
                    background-color: var(--vscode-disabledForeground);
                    cursor: not-allowed;
                }
                .status-text {
                    margin: 10px 0;
                    font-size: 12px;
                    font-weight: bold;
                }
                .status-text.connected {
                    color: var(--vscode-charts-green);
                }
                .status-text.connecting {
                    color: var(--vscode-charts-yellow);
                }
                .status-text.disconnected {
                    color: var(--vscode-charts-red);
                }
                .server-status-text {
                    margin: 10px 0;
                    font-size: 12px;
                    font-weight: bold;
                }
                .server-status-text.running {
                    color: var(--vscode-charts-green);
                }
                .server-status-text.stopped {
                    color: var(--vscode-charts-red);
                }
                h2 {
                    margin: 0 0 15px 0;
                    font-size: 16px;
                    font-weight: 600;
                }
            </style>
        `;

        const scripts = `
            <script>
                const vscode = acquireVsCodeApi();
                let currentTab = 'management';
                let isConnected = false;
                let isConnecting = false;
                let serverStatus = 'stopped';

                function switchTab(tab) {
                    currentTab = tab;
                    updateView();
                }

                function toggleConnection() {
                    vscode.postMessage({ command: 'toggleConnection' });
                }

                function toggleServer() {
                    vscode.postMessage({ command: 'toggleServer' });
                }

                function sendDebug() {
                    const content = document.getElementById('debugInput').value;
                    if (content.trim()) {
                        vscode.postMessage({ command: 'sendDebug', content: content });
                    }
                }

                function sendLuaToJson() {
                    const content = document.getElementById('luaToJsonInput').value;
                    if (content.trim()) {
                        vscode.postMessage({ command: 'sendLuaToJson', content: content });
                    }
                }

                function updateConnectionStatus(status) {
                    const btn = document.getElementById('connectionBtn');
                    const statusText = document.getElementById('statusText');
                    const debugBtn = document.getElementById('debugBtn');
                    const luaToJsonBtn = document.getElementById('luaToJsonBtn');
                    
                    isConnected = status === 'connected';
                    isConnecting = status === 'connecting';
                    
                    if (status === 'connected') {
                        btn.textContent = '停用插件';
                        btn.className = 'connection-button connected';
                        statusText.textContent = '插件状态: 已启用';
                        statusText.className = 'status-text connected';
                        if (debugBtn) debugBtn.disabled = false;
                        if (luaToJsonBtn) luaToJsonBtn.disabled = false;
                    } else if (status === 'connecting') {
                        btn.textContent = '连接中...';
                        btn.className = 'connection-button connecting';
                        statusText.textContent = '插件状态: 连接中...';
                        statusText.className = 'status-text connecting';
                        if (debugBtn) debugBtn.disabled = true;
                        if (luaToJsonBtn) luaToJsonBtn.disabled = true;
                    } else {
                        btn.textContent = '启用插件';
                        btn.className = 'connection-button disconnected';
                        statusText.textContent = '插件状态: 已停用';
                        statusText.className = 'status-text disconnected';
                        if (debugBtn) debugBtn.disabled = true;
                        if (luaToJsonBtn) luaToJsonBtn.disabled = true;
                    }
                }

                function updateServerStatus(status) {
                    const btn = document.getElementById('serverBtn');
                    const statusText = document.getElementById('serverStatusText');
                    
                    serverStatus = status;
                    
                    if (status === 'running') {
                        btn.textContent = '停止服务端';
                        btn.className = 'server-button running';
                        statusText.textContent = '服务端状态: 运行中';
                        statusText.className = 'server-status-text running';
                    } else {
                        btn.textContent = '启动服务端';
                        btn.className = 'server-button stopped';
                        statusText.textContent = '服务端状态: 已停止';
                        statusText.className = 'server-status-text stopped';
                    }
                }

                function openSettings() {
                    vscode.postMessage({ command: 'openSettings' });
                }

                function updateView() {
                    document.querySelectorAll('.tab').forEach(tab => {
                        tab.classList.toggle('active', tab.dataset.tab === currentTab);
                    });
                    
                    document.querySelectorAll('.tab-content').forEach(content => {
                        content.classList.toggle('active', content.id === currentTab + '-content');
                    });
                }

                window.addEventListener('message', event => {
                    const message = event.data;
                    if (message.command === 'updateStatus') {
                        updateConnectionStatus(message.status);
                        updateServerStatus(message.serverStatus);
                    }
                });

                updateView();
            </script>
        `;

        return `
            <!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>面板</title>
                ${styles}
            </head>
            <body>
                <div class="header-container">
                    <div class="tab-container">
                        <div class="tab active" data-tab="management" onclick="switchTab('management')">管理</div>
                        <div class="tab" data-tab="debug" onclick="switchTab('debug')">JS</div>
                        <div class="tab" data-tab="luaToJson" onclick="switchTab('luaToJson')">Lua</div>
                    </div>
                    <div class="settings-icon" onclick="openSettings()" title="打开设置">
                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                            <path d="M12 15.5A3.5 3.5 0 0 1 8.5 12A3.5 3.5 0 0 1 12 8.5a3.5 3.5 0 0 1 3.5 3.5 3.5 3.5 0 0 1-3.5 3.5m7.43-2.53c.04-.32.07-.64.07-.97 0-.33-.03-.66-.07-1l2.11-1.63c.19-.15.24-.42.12-.64l-2-3.46c-.12-.22-.39-.31-.61-.22l-2.49 1c-.52-.39-1.06-.73-1.69-.98l-.37-2.65A.506.506 0 0 0 14 2h-4c-.25 0-.46.18-.5.42l-.37 2.65c-.63.25-1.17.59-1.69.98l-2.49-1c-.22-.09-.49 0-.61.22l-2 3.46c-.13.22-.07.49.12.64L4.57 11c-.04.34-.07.67-.07 1 0 .33.03.65.07.97l-2.11 1.66c-.19.15-.25.42-.12.64l2 3.46c.12.22.39.3.61.22l2.49-1.01c.52.4 1.06.74 1.69.99l.37 2.65c.04.24.25.42.5.42h4c.25 0 .46-.18.5-.42l.37-2.65c.63-.26 1.17-.59 1.69-.99l2.49 1.01c.22.08.49 0 .61-.22l2-3.46c.12-.22.07-.49-.12-.64l-2.11-1.66Z"/>
                        </svg>
                    </div>
                </div>

                <div id="management-content" class="tab-content active">
                    <button id="connectionBtn" class="connection-button disconnected" onclick="toggleConnection()">
                        启用插件
                    </button>
                    <div id="statusText" class="status-text disconnected">插件状态: 已停用</div>
                    
                    <button id="serverBtn" class="server-button stopped" onclick="toggleServer()">
                        启动服务端
                    </button>
                    <div id="serverStatusText" class="server-status-text stopped">服务端状态: 已停止</div>
                </div>

                <div id="debug-content" class="tab-content">
                    <textarea id="debugInput" class="debug-input" placeholder="在此输入js代码..."></textarea>
                    <button id="debugBtn" class="debug-button" onclick="sendDebug()" disabled>
                        执行JS代码
                    </button>
                </div>

                <div id="luaToJson-content" class="tab-content">
                    <textarea id="luaToJsonInput" class="debug-input" placeholder="在此输入Lua代码..."></textarea>
                    <button id="luaToJsonBtn" class="debug-button" onclick="sendLuaToJson()" disabled>
                        执行Lua代码
                    </button>
                </div>

                ${scripts}
            </body>
            </html>
        `;
    }
}
